package com.atguigu.spzx.user.service.impl;

import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.common.constant.Constant;
import com.atguigu.spzx.common.exception.GuiguException;
import com.atguigu.spzx.model.dto.h5.UserLoginDto;
import com.atguigu.spzx.model.dto.h5.UserRegisterDto;
import com.atguigu.spzx.model.entity.user.UserInfo;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.model.vo.h5.UserInfoVo;
import com.atguigu.spzx.user.mapper.UserInfoMapper;
import com.atguigu.spzx.user.service.UserInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class UserInfoServiceImpl implements UserInfoService {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    @Override
    public void register(UserRegisterDto userRegisterDto) {
        //判断数据是否为空
        String username = userRegisterDto.getUsername();
        String password = userRegisterDto.getPassword();
        String code=userRegisterDto.getCode();
        if(!StringUtils.hasText(username)||!StringUtils.hasText(password)||!StringUtils.hasText(code)){
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }

        //判断验证码对不对
        String redisCode = redisTemplate.opsForValue().get(Constant.REDIS_PHONE_CODE + username);
        if(!StringUtils.hasText(redisCode)||!redisCode.equals(code)){
            throw new GuiguException(ResultCodeEnum.VALIDATECODE_ERROR);
        }


        //判断用户名是否存在
        UserInfo userInfo = userInfoMapper.selectUserByUsername(username);
        if (userInfo!=null){
            throw new GuiguException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }

        //没问题，添加新用户
        userInfo=new UserInfo();
        userInfo.setUsername(userRegisterDto.getUsername());
        userInfo.setPassword(DigestUtils.md5DigestAsHex(userRegisterDto.getPassword().getBytes()));
        userInfo.setNickName(userRegisterDto.getNickName());
        userInfo.setAvatar("http://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83eoj0hHXhgJNOTSOFsS4uZs8x1ConecaVOB8eIl115xmJZcT4oCicvia7wMEufibKtTLqiaJeanU2Lpg3w/132");
        userInfo.setStatus(1);
        userInfo.setSex(0);
        userInfoMapper.insertUserInfo(userInfo);

        //删除redis里的验证码
        redisTemplate.delete(Constant.REDIS_PHONE_CODE + username);

    }

    @Override
    public String login(UserLoginDto userLoginDto, String ip) {
        //判断传来的参数有没有问题
        String username=userLoginDto.getUsername();
        String password=userLoginDto.getPassword();
        if(!StringUtils.hasText(username)||!StringUtils.hasText(password)){
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
        //根据用户名查数据库看有没有
        UserInfo userInfo=userInfoMapper.selectUserByUsername(username);
        if (userInfo==null){
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }
        //有数据的话看密码对不对(加密后的)
        if(!DigestUtils.md5DigestAsHex(password.getBytes()).equals(userInfo.getPassword())){
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }
        //判断账户是否被禁用
        if(userInfo.getStatus()==0){
            throw new GuiguException(ResultCodeEnum.ACCOUNT_STOP);
        }

        //成功，更新最后登陆时间和ip
        userInfo.setLastLoginIp(ip);
        userInfo.setLastLoginTime(new Date());
        userInfoMapper.updateUserInfoById(userInfo);

        //对的话生成token,保存到redis，返回token
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        userInfo.setPassword("");
        redisTemplate.opsForValue().set(Constant.REDIS_USER_LOGIN_TOKEN +token, JSON.toJSONString(userInfo),30, TimeUnit.DAYS);
        return token;
    }

    /*@Override
    public UserInfoVo getCurrentUserInfo(String token) {
        String userInfoJSON =redisTemplate.opsForValue().get(Constant.REDIS_USER_LOGIN_TOKEN +token);
        if (!StringUtils.hasText(userInfoJSON)){
            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
        }
        UserInfo userInfo =JSON.parseObject(userInfoJSON,UserInfo.class);
        UserInfoVo userInfoVo=new UserInfoVo();
        *//**
         * userInfoVo.setNickName(userInfo.getNickName());
         * userInfoVo.setAvatar(userInfo.getAvatar());
         *//*
        BeanUtils.copyProperties(userInfo,userInfoVo);
        return userInfoVo;
    }*/
}
